package com.shop.loan.proxy;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageHelper;
import com.shop.loan.mapper.ChannelByMybatisMapper;
import com.shop.loan.mapper.LoanOrderByMybatisMapper;
import com.shop.loan.mapper.UserByMybatisMapper;
import com.shop.loan.model.MachineUser;
import com.shop.loan.model.entity.ChannelByMybatis;
import com.shop.loan.model.entity.LoanOrderByMybatis;
import com.shop.loan.model.entity.UserByMybatis;
import com.shop.loan.model.enums.OrderStatus;
import com.shop.loan.util.Util;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import xyz.erupt.annotation.fun.DataProxy;
import xyz.erupt.annotation.query.Condition;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Map;

@Service
public class MachineUserProxy implements DataProxy<MachineUser> {

    @Resource
    LoanOrderByMybatisMapper loanOrderByMybatisMapper;

    @Resource
    Util util;

    @Resource
    UserByMybatisMapper userByMybatisMapper;

    @Resource
    ChannelByMybatisMapper channelByMybatisMapper;

    @Override
    public String beforeFetch(List<Condition> conditions) {
        conditions.removeIf(condition -> "userName".trim().equals(condition.getKey())
                || "userPhone".trim().equals(condition.getKey()) || "channel".trim().equals(condition.getKey())
                || "channel".trim().equals(condition.getKey()) || "userType".trim().equals(condition.getKey())
                || "machineStatus".trim().equals(condition.getKey()));
        List<Long> userIds = getUserIdBySearch();
        String userIdStr = null;
        if (userIds != null && userIds.size() > 0) {
            userIdStr = org.apache.commons.lang3.StringUtils.join(userIds, ",");
        }
        String sql = "1=1";
        String className = "MachineUser";
        if (StringUtils.hasLength(userIdStr)) {
            sql = sql + " and " + className + ".userId in (" + userIdStr + ")";
        }
        String machineStatus = util.getSearchParam("machineStatus", 0);
        if ("1".trim().equals(machineStatus)) {
            sql = sql + " and " + className + ".score >= 60";
        } else if ("2".trim().equals(machineStatus)) {
            sql = sql + " and " + className + ".score < 60";
        }
        return sql;
    }


    public List<Long> getUserIdBySearch() {
        String userName = util.getSearchParam("userName", 0);
        String userPhone = util.getSearchParam("userPhone", 0);
        String channelIdStr = util.getSearchParam("channel", 0);
        String userTypeStr = util.getSearchParam("userType", 0);
        if (!StringUtils.hasLength(userName) && !StringUtils.hasLength(userPhone) && !StringUtils.hasLength(channelIdStr)
                && !StringUtils.hasLength(userTypeStr)) {
            return new ArrayList<>();
        }
        UserByMybatis userByMybatis = new UserByMybatis();
        userByMybatis.setCardName(userName);
        userByMybatis.setMobile(userPhone);
        if (StringUtils.hasLength(channelIdStr)) {
            userByMybatis.setChannelId(Long.parseLong(channelIdStr));
        }
        if (StringUtils.hasLength(userTypeStr)) {
            userByMybatis.setOrderEndNum(Integer.parseInt(userTypeStr));
        }
        PageHelper.startPage(1, 9999999);
        List<Long> ids = userByMybatisMapper.selectIdByParam(userByMybatis);
        if (ids == null || ids.size() == 0) {
            ids = new ArrayList<>();
            ids.add(-1L);
        }
        return ids;
    }


    @Override
    public void afterFetch(Collection<Map<String, Object>> list) {
        if (list == null || list.size() == 0) {
            return;
        }
        for (Map<String, Object> stringObjectMap : list) {
            Long userId = Long.parseLong(stringObjectMap.get("userId").toString());
            String ruleDetail = stringObjectMap.get("ruleDetail").toString();
            String machineRemark = "";
            if (ruleDetail != null) {
                JSONArray jsonArray = JSON.parseArray(ruleDetail);
                for (Object itemObject : jsonArray) {
                    JSONObject item = JSON.parseObject(itemObject.toString());
                    if (item.getBoolean("hitStatus")) {
                        if (StringUtils.hasLength(machineRemark)) {
                            machineRemark = machineRemark + "\n" + item.getString("desStr");
                        } else {
                            machineRemark = item.getString("desStr");
                        }
                        break;
                    }
                }
                if (!StringUtils.hasLength(machineRemark)) {
                    machineRemark = "机审通过";
                }
            }
            String orderRemark = "";
            LoanOrderByMybatis loanOrderByMybatis = loanOrderByMybatisMapper.selectByLast(userId);
            if (loanOrderByMybatis != null && loanOrderByMybatis.getId() != null) {
                if (loanOrderByMybatis.getStatus() == OrderStatus.wait_loan.getStatus().intValue()) {
                    if (loanOrderByMybatis.getBankId() == null) {
                        orderRemark = "等待绑卡";
                    } else {
                        orderRemark = "等待放款";
                    }
                } else if (loanOrderByMybatis.getStatus() == OrderStatus.wait_auth.getStatus().intValue()) {
                    if (loanOrderByMybatis.getBankId() == null) {
                        orderRemark = "等待绑卡";
                    } else {
                        orderRemark = "等待审核";
                    }
                } else if (loanOrderByMybatis.getStatus() == OrderStatus.underway.getStatus().intValue()) {
                    orderRemark = "待还款";
                } else if (loanOrderByMybatis.getStatus() == OrderStatus.refuse.getStatus().intValue()) {
                    orderRemark = "审核拒绝";
                } else if (loanOrderByMybatis.getStatus() == OrderStatus.refuse_loan.getStatus().intValue()) {
                    orderRemark = "打款拒绝";
                } else if (loanOrderByMybatis.getStatus() == OrderStatus.end.getStatus().intValue()) {
                    orderRemark = "已结清";
                }
            } else {
                orderRemark = "未下单";
            }

            UserByMybatis userByMybatis = userByMybatisMapper.selectByPrimaryKey(userId);
            if (userByMybatis != null) {
                stringObjectMap.put("userInfo", "姓名：" + userByMybatis.getCardName() + "\n 手机号：" + userByMybatis.getMobile() + "\n 身份证：" + userByMybatis.getCardNum());
                if (userByMybatis.getOrderEndNum() == null || userByMybatis.getOrderEndNum() <= 0) {
                    stringObjectMap.put("userType", "0");
                } else {
                    stringObjectMap.put("userType", "1");
                }
                if (userByMybatis.getChannelId() != null) {
                    ChannelByMybatis channelByMybatis = channelByMybatisMapper.selectByPrimaryKey(userByMybatis.getChannelId());
                    if (channelByMybatis != null) {
                        stringObjectMap.put("channel_name", channelByMybatis.getName());
                    }
                }
            }
            stringObjectMap.put("machineRemark", machineRemark);
            stringObjectMap.put("orderRemark", orderRemark);
            stringObjectMap.put("id", userId);
        }
    }


}
